<template>
  <div>
    <!-- 三级分类全局组件 -->
    <Category :sence="sence" />
    <el-card style="margin: 10px 0px">
      <div v-if="sence == 0">
        <el-button
          type="primary"
          size="default"
          icon="Plus"
          :disabled="categoryStore.c3Id ? false : true"
          @click="addAttribute"
          >添加属性</el-button
        >
        <el-table border :data="attrArr" style="margin: 10px 0px">
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="120px"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-tag
                style="margin: 5px"
                v-for="(item, index) in row.attrValueList"
                :key="item.id"
                >{{ item.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px">
            <!-- row：已有的属性对象 -->
            <template #="{ row, $index }">
              <!-- 修改已有属性的按钮 -->
              <el-button
                type="primary"
                size="small"
                icon="Edit"
                @click="handleEmit(row)"
              ></el-button>
              <el-popconfirm
                :title="`你确定删除${row.attrName}?`"
                width="200px"
                @confirm="handleDel(row.id)"
              >
                <template #reference>
                  <el-button
                    type="primary"
                    size="small"
                    icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="sence == 1">
        <!-- 展示添加属性与修改数据的结构 -->
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input
              v-model="attrParams.attrName"
              placeholder="请你输入属性名称"
            ></el-input>

          </el-form-item>
        </el-form>
        <el-button
          :disabled="!attrParams.attrName"
          type="primary"
          size="default"
          icon="Plus"
          @click="addValue"
          >添加属性值</el-button
        >
        <!-- <el-button type="primary" size="default">取消</el-button> -->
        <el-table
          border
          :data="attrParams.attrValueList"
          style="margin: 10px 0px"
        >
          <el-table-column
            label="序号"
            width="80px"
            type="index"
            align="center"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <!-- row:即为当前属性值对象 -->
            <template #="{ row, $index }">
              <el-input
                v-if="row.flag"
                :ref="(vc:any)=> refInput[$index] = vc"
                v-model="row.valueName"
                size="small"
                placeholder="请你输入属性值名称"
                @blur="toLook(row,$index)"
              ></el-input>
              <div v-else @click="toEdit(row,$index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          
          <el-table-column label="属性值操作">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                size="small"
                icon="Delete"
                @click="attrParams.attrValueList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" size="default" :disabled="!attrParams.attrValueList.length" @click="save">保存</el-button>
        <el-button type="primary" size="default" @click="cancel"
          >取消</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { watch, ref, reactive,nextTick,onBeforeUnmount  } from "vue";
import { reqAttr, reqAddOrUpdateAttr,reqRemoveAttr } from "@/api/product/attr/index";
import useCategoryStore from "@/store/modules/category";
import type { AttrResponseData, Attr,AttrValue } from "@/api/product/attr/type";
import { ElMessage } from "element-plus";
let refInput =ref<any>([])
let categoryStore = useCategoryStore();
let attrArr = ref<Attr[]>([]);
let sence = ref<number>(0);
// 收集新增属性
let attrParams = reactive<Attr>({
  attrName: "", //新增的属性的名字
  attrValueList: [
    //新增的属性值数组
  ],
  categoryId: "", //三级分类的ID
  categoryLevel: 3, //代表的是三级分类
});
watch(
  () => categoryStore.c3Id,
  () => {
    attrArr.value = [];
    if (!categoryStore.c3Id) return;
    getAttr();
  }
);
//获取已有的属性与属性值方法
const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore;
  let result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id);
  attrArr.value = result.data;
};
const addValue = () => {
  attrParams.attrValueList.push({
    valueName: "",
    flag:true
  });
  nextTick(()=>{
    refInput.value[attrParams.attrValueList.length-1].focus()
  })
};
const cancel = () => {
  sence.value = 0;
};
// 修改
const handleEmit = (row:Attr) => {
  sence.value = 1;
  console.log(row)
  // attrParams.attrName = row.attrName
  // attrParams.attrValueList = row.attrValueList
  // attrParams.id = row.id
  Object.assign(attrParams,JSON.parse(JSON.stringify(row)))
};
const handleDel = async (id:number)=>{
  let result:any = await reqRemoveAttr(id)
  if(result.code==200){
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    getAttr()
  }else{
    ElMessage({
      type: "error",
      message: "删除失败",
    });
  }
}
const addAttribute = () => {
  sence.value = 1;
  Object.assign(attrParams, {
    attrName: "",
    attrValueList: [],
    categoryId: "", 
    categoryLevel: 3,
  });
};
// 新增保存
const save = async () => {
  attrParams.categoryId = categoryStore.c3Id;
  let result: any = await reqAddOrUpdateAttr(attrParams);
  if (result.code == 200) {
    sence.value = 0;
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改成功" : "新增成功",
    });
    getAttr();
  } else {
    ElMessage({
      type: "success",
      message: attrParams.id ? "修改成功" : "新增成功",
    });
  }
};
// 失去焦点查看
const toLook = (row:AttrValue,$index:number)=>{
  if(row.valueName.trim()==''){
    attrParams.attrValueList.splice($index,1)
    ElMessage({
      type:'error',
      message:'属性值不能为空'
    })
    return
  }
  let result = attrParams.attrValueList.find(item=>{
    if(item!=row){
      return item.valueName === row.valueName
    }
  })
  if(result){
    attrParams.attrValueList.splice($index,1)
    ElMessage({
            type: 'error',
            message: '属性值不能重复'
        })
        return;
  }
  row.flag = false
}
//属性值div点击事件
const toEdit = (row:AttrValue,$index:number)=>{
  row.flag = true
  nextTick(()=>{
    refInput.value[$index].focus()
  })
}
//路由组件销毁的时候，把仓库分类相关的数据清空
onBeforeUnmount(() => {
  categoryStore.$reset()
})
</script>

<style scoped></style>
